package cn.bluethink.eguan.core.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.bluethink.eguan.core.security.Token;
import cn.bluethink.eguan.core.service.EgPosObjectService;
import cn.bluethink.eguan.core.service.EgUserService;
import cn.bluethink.eguan.core.util.DingUtil;
import cn.bluethink.eguan.model.core.EgCheckStatus;
import cn.bluethink.eguan.model.core.EgConfigInfo;
import cn.bluethink.eguan.model.core.EgOType;
import cn.bluethink.eguan.model.core.EgObject;
import cn.bluethink.eguan.model.core.EgRole;
import cn.bluethink.eguan.model.core.EgUser;
import cn.bluethink.eguan.result.ResponseMessage;
import cn.bluethink.eguan.result.ResponseResult;
import cn.bluethink.eguan.utils.TokenManager;

/**
 * 驿馆用户 管理器
 * 
 * @title 苏州中科蓝迪公司所有(c)2016-2021
 * @version 0.1.0
 * @describe
 * @author liuxn
 * @date 2018年8月17日
 * @note 修订历史： （1）liuxn于2018年8月17日构建初始版本0.1 （2）liuxn于2018年10月09日添加钉钉登录方法，
 *       （3）liuxn于2018年10月09日添加session存储token、unionId、获取token时间方法 storageSession
 *       （4）liuxn于2018年10月22日修订更新用户基本信息接口
 */
@CrossOrigin
@RestController
@RequestMapping("/eguan/v1.0/user")
public class EgUserController {

    @Autowired
    private DingUtil dingutil;
    
    @Autowired
    private TokenManager tokenManager;
    
    @Autowired
    private HttpServletRequest request;
    
    @Autowired
    private EgConfigInfo configInfo;

    @Autowired
    private EgUserService userService;

    @Autowired
    private EgPosObjectService posObjectService;

    /**
     * 钉钉扫码登录跳转登录url，如果用户不存在会新建一个用户
     * 
     * @return 获取钉钉token和用户所在pos
     * @throws Exception
     */
    @GetMapping("/ddlogin")
    public ResponseResult<Map<String, Object>> ddlogin(@RequestParam String code) throws Exception {
        // 注意用户那只能存储持久授权码，并由前台传入后台进行计算
        DingUtil.DingUser dinguser = dingutil.getDingUser(code);
        if (dinguser == null)
            return new ResponseResult<>(ResponseMessage.LOGIN_FAIL);
       // String persistentCode = dinguser.persistentCode();
        // String openid = dinguser.openId();
        String unionid = dinguser.unionId();
        String nick = dinguser.nick();
        String avatar = dinguser.avatar();
        String corpid = dinguser.corpId();
        String corpname = dinguser.corpName();

        EgUser user = userService.findByUserId(unionid);
        if (user == null || user.getId() == 0) { // 数据库中找不到用户，则新建一个
            user = userService.create(nick, avatar, unionid, corpid, corpname);
            if (user == null) // 新建用户失败，则登录失败
                return new ResponseResult<>(ResponseMessage.LOGIN_FAIL);
        } else {
            int checkstatus = user.getCheckStatus();
            if (checkstatus == EgCheckStatus.STATUS_NOPASS) // 审核不通过的用户不许登录
                return new ResponseResult<>(ResponseMessage.LOGIN_ILLEGAL_USER);
        }

        EgObject pos = posObjectService.pos(user.getPos().getType().getOtid(), user.getPos().getId());
        if (pos == null)
        	 pos = new EgObject(0L, null, configInfo.otypes().get(EgOType.JIANGHU));
     
        String strToken = tokenManager.createToken(user.getId());

        Map<String, Object> result = new HashMap<>();
        result.put("token", strToken);
        result.put("pos", pos);
        return new ResponseResult<>(ResponseMessage.OK, result);
    }

    /**
     * 用户退出登录
     * 
     * @return 返回用户退出成功
     * @throws Exception
     */
    @Token
    @GetMapping("/logout")
    public ResponseResult<String> logout() throws Exception {
        String token = request.getHeader("Authorization");
        tokenManager.removeToken(token);
        return new ResponseResult<>(ResponseMessage.OK);
    }

    /**
     * 更新登录用户基本信息 （包括用户的名称、头像）
     * 
     * @param user
     *            用户对象
     * @return
     * @throws Exception
     */
    @Token
    @PostMapping("/update")
    public ResponseResult<EgUser> update(@RequestBody EgUser user) throws Exception {
        // 被更新用户ID不能为空
        if (user == null || !user.isValidate()) {
            return new ResponseResult<>(ResponseMessage.NOTNULL_ID);
        }
        //String token = request.getHeader("Authorization");
        Long id = (Long)request.getAttribute("userId");
        // 根据参数中的用户ID查询是否存在要修改的用户
        EgUser egUser = userService.getUser(id, false);
        if(egUser == null) return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
        // 被更新用户是当前登录用户
        if (id.equals(egUser.getId())) {
        	// 不更新当前用户角色
        	user.setRole(null);
            return new ResponseResult<>(ResponseMessage.OK, userService.update(user));
        }
        return new ResponseResult<>(ResponseMessage.UPDATE_FAIL);
    }

    /**
     * 获取登录用户自己的角色信息
     * 
     * @return
     * @throws Exception
     */
    @Token
    @GetMapping("/mypurview")
    public ResponseResult<EgUser> mypurview() throws Exception {
        //String token = request.getHeader("Authorization");
    	Long uid = (Long)request.getAttribute("userId");
        EgRole role = userService.mypurview(uid);
        if (role == null) {
            return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
        }
        EgUser user = new EgUser(uid,null,null);
        user.setRole(role);
        return new ResponseResult<>(ResponseMessage.OK,user);
        
    }

    /**
     * 查看用户详情信息 包括基本信息(角色、账户等)以及用户位置的详细信息
     * 
     * @param id
     *            用户ID
     * @return
     * @throws Exception
     */
    @Token
    @GetMapping("/detail")
    public ResponseResult<EgUser> detail(@RequestParam Long id) throws Exception {
        // 根据ID查询用户详细信息
        EgUser user = userService.detail(id);
        if (user != null) {
            return new ResponseResult<>(ResponseMessage.OK, user);
        }
        return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
    }

    /**
     * 获取用户自己的信息 (基本信息或详细信息)
     * 
     * @param bDetail
     *            是否查询详情
     * @return
     * @throws Exception
     */
    @Token
    @GetMapping("/mine")
    public ResponseResult<EgUser> mine(@RequestParam Boolean bDetail) throws Exception {
        //String token = request.getHeader("Authorization");
        Long id = (Long)request.getAttribute("userId");

        EgUser user = userService.getUser(id, bDetail);
        if (user != null) {
            return new ResponseResult<>(ResponseMessage.OK, user);
        }
        return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
    }

    @RequestMapping(value = "toALiDingDing")
    public void toALiDingDing(HttpServletResponse response) throws Exception {
        String url = "http://localhost:9998/dist/#/111";
    //    String url = "http://116.62.28.103:8000/dist/#/111";
    //	String url = "http://www.eguan.work/dist/#/111";
        String ecode = URLEncoder.encode(url, "UTF-8");

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("https://oapi.dingtalk.com/connect/qrconnect?appid=dingoaazenbo1aatczriie&")
                .append("response_type=code&scope=snsapi_login&state=STATE").append("&redirect_uri=" + ecode);
        // .append(timeUtil.getCurrentTimeNanosOrMillis())
        try {
            response.sendRedirect(stringBuilder.toString());
        } catch (IOException e1) {
        }
    }

}
